from typing import Dict, Any
from langgraph.graph import StateGraph
from pydantic import BaseModel, Field, ValidationError
from intelli_port.integrations.rebook import rebook_order


class ServiceRebook(BaseModel):
    type: str = Field(default="rebook")
    rebook_status: str
    order_id: str | None = None


def build_rebook_subgraph():
    g = StateGraph(dict)

    def exec_rebook(state: Dict[str, Any]) -> Dict[str, Any]:
        slots = state.get("slots") or {}
        rb = rebook_order(slots)
        try:
            svc = ServiceRebook.model_validate({"type": "rebook", "rebook_status": rb.get("status", "succeeded"), "order_id": rb.get("order_id")}).model_dump()
        except ValidationError:
            svc = {"type": "rebook", "rebook_status": "failed", "order_id": None}
        return {**state, "service": svc}

    g.add_node("rebook", exec_rebook)
    g.set_entry_point("rebook")
    return g.compile()